package org.dht.com.tra;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * The <code>ReturnsManagerCommunication</code> class is responsible for
 * management the responses for the messages. The
 * {@code ReturnsManagerCommunication} use WaitingResults objects for having a
 * reference of the messages.
 */
public class ReturnsManagerCommunication<T> implements ReturnsManager<T> {

	/**
	 * The map of the WaitingResult references with a specific sequence number
	 */
	private Map<Long, WaitingResult<T>> results;

	/**
	 * Create a synchronized instance of the class HashMap
	 */

	ReturnsManagerCommunication() {
		results = Collections
				.synchronizedMap(new HashMap<Long, WaitingResult<T>>());
	}

	/**
	 * Creates a WaitingResult object for the message with the specified
	 * sequence number
	 * 
	 * @param sequence
	 *            . The sequence number of the message
	 * @return Returns the {@link WaitingResult} created
	 */
	public WaitingResult<T> createWaitingResult(long sequence, long timeOut) {
		WaitingResult<T> resultInWait = new WaitingResult<T>(sequence, this,
				timeOut);

		results.put(sequence, resultInWait);

		return resultInWait;
	}

	/**
	 * This method is responsible for releasing the WaitingResult reference with
	 * the specified sequence number by set the response for the message.
	 * 
	 * @param sequence
	 *            . The sequence number of the message
	 * @param result
	 *            . The response for the message
	 */
	public synchronized void releaseWaitingResult(long sequence, T result) {
		if (results.get(sequence) == null) {
			return;
		}
		results.remove(sequence).setResult(result);
	}
}
